﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using UnityEngine;

/// <summary>
/// 游戏服务器参数
/// </summary>
public class GameServerConfig
{
   public class Server
    {
        public string name;
        public string httpServer;

        public string gameServer;
        public int gameServerPort;
        
        public string battleServer;
        public int battleServerPort;
        
        public string walkServer;
        public int walkServerPort;

        public override string ToString()
        {
            return $"nsme:{name}  gameServer:{gameServer}";
        }
    }

    /// <summary>
    /// 存放资源和配置的 http服务器地址
    /// </summary>
    //public static string httpServer = "18.179.131.241";
    
    /// <summary>
    /// 服务器参数列表，运行时会使用下载到本地的服务器参数配置初始化这个列表
    /// </summary>
    public Server[] servers 
    {

        get
        {
          //  #if UNITY_EDITOR
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[ipHostInfo.AddressList.Length - 1];
            string ipStr = ipAddress.ToString();

/*            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                Server[] list = new Server[]
                            {
                                new Server()
                                {
                                    name = "本地",
                                    httpServer = ipStr,
                
                                    gameServer = ipStr,
                                    gameServerPort = 555,
                
                                    battleServer = ipStr,
                                    battleServerPort = 576,
                
                                    walkServer = ipStr,
                                    walkServerPort = 586,
                                },
                            };
                 return list;
            }
            else*/
            {
                return new Server[]
                {
                    new Server()
                    {
                        name = ""
                    }
                    , 
                    new Server()
                    {
                        name = "本地",
                        httpServer = ipStr,
                
                        gameServer = ipStr,
                        gameServerPort = Port_GameServer,
                
                        battleServer = ipStr,
                        battleServerPort = Port_BattleServer,
                
                        walkServer = ipStr,
                        walkServerPort = Port_WalkServer,
                    },
                    new Server()
                    {
                        name = "家里",
                        httpServer = "192.168.0.102",

                        gameServer = "192.168.0.102",
                        gameServerPort = Port_GameServer,

                        battleServer = "192.168.0.102",
                        battleServerPort = Port_BattleServer,

                        walkServer = "192.168.0.102",
                        walkServerPort = Port_WalkServer,
                    },
                    new Server()
                    {
                        name = "阿里云测试服",
                        httpServer = "115.29.67.138",

                        gameServer = "115.29.67.138",
                        gameServerPort = Port_GameServer,

                        battleServer = "115.29.67.138",
                        battleServerPort = Port_BattleServer,

                        walkServer = "115.29.67.138",
                        walkServerPort = Port_WalkServer,
                    },
                    new Server()
                    {
                        name = "上海",
                        httpServer = "47.116.71.103",
                        gameServer = "47.116.71.103",
                        gameServerPort = Port_GameServer,
                        battleServer = "47.116.71.103",
                        battleServerPort = Port_BattleServer,
                        walkServer = "47.116.71.103",
                        walkServerPort = Port_WalkServer,
                    },
                    new Server()
                    {
                        name = "ClientLog香港",
                        httpServer = "5.188.230.89",
                        gameServer = "5.188.230.89",
                        gameServerPort = Port_GameServer,
                        battleServer = "5.188.230.89",
                        battleServerPort = Port_BattleServer,
                        walkServer = "5.188.230.89",
                        walkServerPort = Port_WalkServer,
                    },
                    new Server()
                    {
                        name = "香港",
                        httpServer = "8.210.230.213",
                        gameServer = "8.210.230.213",
                        gameServerPort = Port_GameServer,
                        battleServer = "8.210.230.213",
                        battleServerPort = Port_BattleServer,
                        walkServer = "8.210.230.213",
                        walkServerPort = Port_WalkServer,
                    },
                    new Server()
                    {
                        name = "新加坡",
                        httpServer = "161.117.234.183",
                        gameServer = "161.117.234.183",
                        gameServerPort = Port_GameServer,
                        battleServer = "161.117.234.183",
                        battleServerPort = Port_BattleServer,
                        walkServer = "161.117.234.183",
                        walkServerPort = Port_WalkServer,
                    },
                    new Server()
                    {
                        name = "印度",
                        httpServer = "149.129.130.255",
                        gameServer = "149.129.130.255",
                        gameServerPort = Port_GameServer,
                        battleServer = "149.129.130.255",
                        battleServerPort = Port_BattleServer,
                        walkServer = "149.129.130.255",
                        walkServerPort = Port_WalkServer,
                    },
                    new Server()
                    {
                        name = "吉隆坡",
                        httpServer = "47.254.216.60",
                        gameServer = "47.254.216.60",
                        gameServerPort = Port_GameServer,
                        battleServer = "47.254.216.60",
                        battleServerPort = Port_BattleServer,
                        walkServer = "47.254.216.60",
                        walkServerPort = Port_WalkServer,
                    },
                    new Server()
                    {
                        name = "雅加达",
                        httpServer = "147.139.175.78",
                        gameServer = "147.139.175.78",
                        gameServerPort = Port_GameServer,
                        battleServer = "147.139.175.78",
                        battleServerPort = Port_BattleServer,
                        walkServer = "147.139.175.78",
                        walkServerPort = Port_WalkServer,
                    }
                };
                
            }
            //#endif
        }
    }

    public const int Port_GameServer = 1555;
    public const int Port_BattleServer = 1576;
    public const int Port_WalkServer = 1586;
    
    const string KEY_gameServer = "KEY_gameServer";
    const string KEY_gameServerPort = "KEY_gameServerPort";
    const string KEY_battleServer = "KEY_battleServer";
    const string KEY_battleServerPort = "KEY_battleServerPort";

    Server m_CurServer;
    public Server curServer { get { return m_CurServer; } }

    /// <summary>
    /// 游戏服务器
    /// </summary>
    public string gameServer { get { return m_CurServer.gameServer; } }
    public int gameServerPort { get { return m_CurServer.gameServerPort; } }
    /// <summary>
    /// 战斗服务器，由游戏服务器返回
    /// </summary>
    public string battleServer { get { return m_CurServer.battleServer; } }
    public int battleServerPort { get { return m_CurServer.battleServerPort; } }
    
    /// <summary>
    /// 闲逛服务器
    /// </summary>
    public string walkServer { get { return m_CurServer.walkServer; } }
    public int walkServerPort { get { return m_CurServer.walkServerPort; } }
    
    int serverNum { get { return servers.Length; } }
    
    public string curServerName { get { return m_CurServer.name; } }

    /// <summary>
    /// 当前选择的是第几个服务器
    /// </summary>
    public int curServerType
    {
        get
        {
            for (int i = 0; i < servers.Length; ++i)
            {
                if (servers[i].Equals(m_CurServer))
                    return i;
            }

            //GameDebug.LogError("没在servers中找到对应的m_CurServer,逻辑有问题");
            return 0;
        }
    }

    public int GetServerIndexByName(string serverName)
    {
        for (int i = 0; i < servers.Length; ++i)
        {
            if (serverName.Equals(servers[i].name))
                return i;
        }

        GameDebug.Log($"没在servers中找到对应的m_CurServer  serverName：{serverName}  servers:{servers.GetArrStr()}");
        return 1;
    }

    /// <summary>
    /// 解析服务器json参数
    /// </summary>
    //public bool ParseServerParam(string configPath,Action updateServerParam)
//    {
//        string json = "";

//        try
//        {
//            bool result = false;

//            if (System.IO.File.Exists(configPath))
//            {
//                json = System.IO.File.ReadAllText(configPath).Trim();
//                if (string.IsNullOrEmpty(json) || json.Length == 0)
//                {
//                    result = false;
//                }
//                else
//                {
//                    servers = Newtonsoft.Json.JsonConvert.DeserializeObject<Server[]>(json);
//                    if (servers != null)
//                    {
//                        Load();
//                        GameDebug.Log(string.Format("服务器参数初始化完成,服务器ip个数为:{0}", servers.Length));
//                        result = true;
//                    }else
//                    {
//                        GameDebug.LogError("解析服务器参数出错1,json:\n" + json);
//                        result = false;
//                    }
//                }
//            }
//            else
//            {
//                GameDebug.LogError("服务器参数配置文件不存在,path:" + configPath);
//                result = false;
//            }

//            if(!result)
//            {
//                Game.instance.GetActiveSceneNav().LoadDisplay<NoticePanelDisplayController>((p) =>
//                { p.Init(new NoticePanelData(Localization.instance.GetValue("base_tips"), Localization.instance.GetValue("base_server_param_param_fail"), Localization.instance.GetValue("base_confirm"), "", updateServerParam, null)); }, false);
//                return false;
//            }
//            else
//            {
//                return true;
//            }
//        }
//        catch (System.Exception e)
//        {
//            Game.instance.GetActiveSceneNav().LoadDisplay<NoticePanelDisplayController>((p) => 
//            { p.Init(new NoticePanelData(Localization.instance.GetValue("base_tips"), Localization.instance.GetValue("base_server_param_param_fail"), Localization.instance.GetValue("base_confirm"), "", updateServerParam, null)); }, false);

//            GameDebug.Log($"serverParam json:{json}");
////#if UNITY_EDITOR
////            string filePath = appPath + "/Debugger/ServerParamLog/ServerParam.txt";           
////            string dirName = System.IO.Path.GetDirectoryName(filePath);
////            if(!System.IO.Directory.Exists(dirName))
////            {
////                System.IO.Directory.CreateDirectory(dirName);
////            }

////            System.IO.File.WriteAllText(filePath, json);
////            UnityEditor.AssetDatabase.Refresh();
////#endif
//            GameDebug.LogError("解析服务器参数出错2:" + e);
//            return false;
//        }
//    }

    public void SetServerType(int index)
    {
        int maxValue = serverNum - 1;
        index = UnityEngine.Mathf.Clamp(index, 0, maxValue);
        m_CurServer = servers[index];
        StaticSetServerType(index);
    }

    public void StaticSetServerType(int type)
    {
        //UnityEngine.PlayerPrefs.SetInt("KEY_NET_SERVER_SET", type);
        GameDebug.Log($"选择服务器  index：{type}  name：{servers[type].name}");
        UnityEngine.PlayerPrefs.SetString("KEY_NET_SERVER_NAME_SET", servers[type].name);
    }

    /// <summary>
    /// 获取到数据服务器的地址
    /// </summary>
    /// <returns></returns>
    public List<string> GetDataServers()
    {
        List<string> dataServers = new List<string>();
        string serverName = UnityEngine.PlayerPrefs.GetString("KEY_NET_SERVER_NAME_SET");
        int serverIndex = ContainServer(serverName);
        if (serverIndex != -1)//找到了当前对应服务器
        {
            dataServers.Add(servers[serverIndex].httpServer);
        }
        else
        {
            for (int i = 0; i < servers.Length; ++i)
            {
                if (i == 0)
                {
                    dataServers.Add(servers[i].httpServer);
                }
                else
                {
#if UNITY_EDITOR || DEBUG
                    dataServers.Add(servers[i].httpServer);
#endif
                }
            }
        }

        if (dataServers.Count == 0)
            GameDebug.LogError("数据服务器地址列表为空，无法获取到数据配置");
        return dataServers;
    }

    int ContainServer(string serverName)
    {
        if (string.IsNullOrEmpty(serverName))
            return -1;

        for (int i = 0; i < servers.Length; ++i)
        {
            if (servers[i].name.Equals(serverName))
                return i;
        }

        return -1;
    }

    public GameServerConfig()
    {
        Load();
    }

    void Load()
    {
        string serverName = UnityEngine.PlayerPrefs.GetString("KEY_NET_SERVER_NAME_SET");
        int serverTypeValue = GetServerIndexByName(serverName);
        int maxValue = serverNum - 1;
        serverTypeValue = UnityEngine.Mathf.Clamp(serverTypeValue, 0, maxValue);

        GameDebug.Log($"serverTypeValue:{serverTypeValue}");
        m_CurServer = servers[serverTypeValue];
    }

    void SaveGameServer()
    {
        UnityEngine.PlayerPrefs.SetString(KEY_gameServer, m_CurServer.gameServer);
        UnityEngine.PlayerPrefs.SetInt(KEY_battleServerPort, m_CurServer.gameServerPort);
    }

    void SaveBattleServer()
    {
        UnityEngine.PlayerPrefs.SetString(KEY_battleServer, m_CurServer.battleServer);
        UnityEngine.PlayerPrefs.SetInt(KEY_battleServerPort, m_CurServer.battleServerPort);
    }

    /// <summary>
    /// 从数据配置获取到游戏服务器地址进行更新
    /// </summary>
    /// <param name="gameServer"></param>
    /// <param name="gameServerPort"></param>
    public void UpdateGameServer(string gameServer,int gameServerPort)
    {
        m_CurServer.gameServer = gameServer;
        m_CurServer.gameServerPort = gameServerPort;
    }

    public void UpdateBattleServer(string battleServer, int battleServerPort)
    {
        m_CurServer.battleServer = battleServer;
        m_CurServer.battleServerPort = battleServerPort;
    }

    /// <summary>
    /// 客户端Assets同级目录
    /// </summary>
    static string appPath
    {
        get
        {
#if UNITY_EDITOR
            return Application.dataPath.Substring(0, Application.dataPath.Length - ("/Assets").Length);
#endif
            return "";
        }
    }

}